package com.luotat.productservice.controller;

import com.luotat.pojo.result.Result;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.luotat.productservice.mapper.ProductMapper;
import com.luotat.pojo.product.Product;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 商品的服务控制层
 */
@AllArgsConstructor
@RestController
@Slf4j
@RequestMapping("/api/product")
public class ProductController
{
    private final ProductMapper productMapper;

    /**
     * 添加商品
     */
    @PostMapping
    public Result insert(@RequestBody Product product)
    {
        try
        {
            productMapper.insert(product);
            log.info("添加商品成功: {}", product.getProductName());
            return Result.success("商品添加成功");
        }
        catch (DuplicateKeyException e)
        {
            log.error("商品名已存在: {}", product.getProductName(), e);
            return Result.error("商品名已存在");
        }
    }

    /**
     * 删除商品
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Integer id)
    {
        productMapper.delete(id);
        log.info("删除商品成功: {}", id);
        return Result.success("删除商品成功");
    }

    // 修改商品
    @PutMapping
    public Result update(@RequestBody Product product)
    {
        try
        {
            productMapper.update(product);
            log.info("修改商品成功: {}", product.getProductName());
            return Result.success("修改商品成功");
        }
        catch (DuplicateKeyException e)
        {
            log.error("商品名已存在: {}", product.getProductName(), e);
            return Result.error("商品名已存在");
        }
    }

    /**
     * 根据id查询商品
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable("id") Integer id)
    {
        Product product = productMapper.getById(id);
        log.info("查询商品成功: {}", product.getProductName());
        return Result.success(product, "查询商品成功");
    }

    /**
     * 查询所有商品
     */
    @GetMapping("/getAll")
    public Result getAll()
    {
        List<Product> productList = productMapper.getAll();
        log.info("查询所有商品成功: {}", productList.size());
        return Result.success(productList, "查询所有商品成功");
    }
}